Ext
		.define('Packt.controller.Login',
				{ // #1
					extend : 'Ext.app.Controller', // #2
					requires : [ 'Packt.util.MD5', 'Packt.util.Util' ],
					views : [ 'Login', 'Header' ],

					init : function(application) {
						this.control({
							"login form button#submit" : { // #1
								click : this.onButtonClickSubmit
							// #2
							},
							"login form button#cancel" : { // #3
								click : this.onButtonClickCancel
							// #4
							},
							"appheader button#logout" : {
								click : this.onButtonClickLogout
							}
						});
					},
					onButtonClickSubmit : function(button, e, options) {
						console.log('login submit'); // #5
						var formPanel = button.up('form'), login = button.up('login'), user = formPanel.down('textfield[name=user]')
								.getValue(), pass = formPanel.down('textfield[name=password]').getValue();
						pass = Packt.util.MD5.encode(pass);
						if (formPanel.getForm().isValid()) {
							Ext.get(login.getEl()).mask("Authenticating... Please wait...", 'loading');
							Ext.Ajax.request({
								url : 'http://localhost:8080/masteringextjs/rest/json/user/login',
								params : {
									user : user,
									password : pass
								},
								success : function(conn, response, options, eOpts) {
									Ext.get(login.getEl()).unmask();
									var result = Packt.util.Util.decodeJSON(conn.responseText);
									if (result.success) { // #3
										login.close(); // #4
										Ext.create('Packt.view.MyViewport'); // #5
									} else {
										Packt.util.Util.showErrorMsg(conn.responseText);
									}
								},
								failure : function(conn, response, option, eOpts) {
									Ext.get(login.getEl()).unmask();
									Packt.util.Util.showErrorMsg(conn.responseText);
								}
							});
						}
					},

					onButtonClickCancel : function(button, e, options) {
						button.up('form').getForm().reset();
					},

					onButtonClickLogout : function(button, e, options) {
						Ext.Ajax.request({
							url : 'http://localhost:8080/masteringextjs/rest/json/user/logout',
							success : function(conn, response, options, eOpts) {
								var result = Packt.util.Util.decodeJSON(conn.responseText);
								if (result.success) {
									button.up('mainviewport').destroy();
									window.location.reload();
								} else {
									Packt.util.Util.showErrorMsg(conn.responseText);
								}
							},
							failure : function(conn, response, options, eOpts) {
								Packt.util.Util.showErrorMsg(conn.responseText);
							}
						});
					}
				});
